package com.stox.charting.ui.swing.event.listener;

import prefuse.util.ui.JRangeSlider;

import com.stox.charting.ui.swing.event.ChartModelChangedEvent;
import com.stox.charting.ui.swing.model.Axis;
import com.stox.charting.ui.swing.model.ChartModel;
import com.stox.charting.ui.swing.model.ChartModel.ChartModelListener;
import com.stox.charting.ui.swing.model.DefaultAxis;
import com.stox.charting.ui.swing.model.indicator.VolumeChart;
import com.stox.charting.ui.swing.model.price.PriceChart;
import com.stox.charting.ui.swing.model.price.PriceChartView;

public class ViewportChangedEventListener implements ChartModelListener {

	@Override
	public void chartModelChanged(ChartModelChangedEvent event) {
		if(event.getProperty().equalsIgnoreCase("viewport")){
			ChartModel<?> chartModel = (ChartModel<?>)event.getSource();
			updateViewport(chartModel);
			
			if(chartModel.getChart().getChartView() instanceof PriceChartView){
				PriceChartView view = (PriceChartView)chartModel.getChart().getChartView();
				
				if(chartModel.getChart() instanceof PriceChart){
					view.getPriceAxis().update(chartModel.getViewport().getMaximumValueVisible(), chartModel.getViewport().getMinimumValueVisible());
				}
				if(chartModel.getChart() instanceof VolumeChart){
					view.getVolumeAxis().update(chartModel.getViewport().getMaximumValueVisible(), chartModel.getViewport().getMinimumValueVisible());
				}
			}else{
				for(int i = 0; i < chartModel.getChart().getChartView().getAxesCount(); i++){
					Axis axis = chartModel.getChart().getChartView().getAxis(i);
					
					if(axis instanceof DefaultAxis){
						DefaultAxis defaultAxis = (DefaultAxis)axis;
						defaultAxis.update(
								chartModel.getViewport().getMaximumValueVisible(), 
								chartModel.getViewport().getMinimumValueVisible());
					}
				}
			}
		}
	}


	private void updateViewport(ChartModel<?> chartModel){
		JRangeSlider rangeSlider = chartModel.getChart().getChartView().getChartingInternalFrameView().getRangeSlider();
		
		int high = rangeSlider.getHighValue();
		int low = rangeSlider.getLowValue();
		int minimum = rangeSlider.getMinimum();
		int maximum = rangeSlider.getMaximum();
		
		chartModel.getViewport().update(high, low, minimum, maximum);
	}
	
	
}
